package lac.serviceuint.job.quartz;

import java.lang.reflect.Field;

import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.utils.Key;

public class ServiceUnitJobBuilder extends JobBuilder{

	private JobKey key;
    private String description;
    private Class<? extends Job> jobClass;
    private boolean durability;
    private boolean shouldRecover;
    private JobDataMap jobDataMap = new JobDataMap();
	private Job job;
	
	
	public static ServiceUnitJobBuilder newJob() {
        return new ServiceUnitJobBuilder();
    }

	public ServiceUnitJobBuilder setJob(Job job) {
		this.jobClass = job.getClass();
		this.job = job;
		return this;
	}

	public ServiceUnitJobDetail build() {
		try {
			Field keyField =JobBuilder.class.getDeclaredField("key");
			Field descriptionField =JobBuilder.class.getDeclaredField("description");
			Field jobClassField =JobBuilder.class.getDeclaredField("jobClass");
			Field durabilityField =JobBuilder.class.getDeclaredField("durability");
			Field shouldRecoverField =JobBuilder.class.getDeclaredField("shouldRecover");
			Field jobDataMapField =JobBuilder.class.getDeclaredField("jobDataMap");
			keyField.setAccessible(true);
			descriptionField.setAccessible(true);
			jobClassField.setAccessible(true);
			durabilityField.setAccessible(true);
			shouldRecoverField.setAccessible(true);
			jobDataMapField.setAccessible(true);
			key = (JobKey) keyField.get(this);
			description = (String) descriptionField.get(this);
			durability = (boolean) durabilityField.get(this);
			shouldRecover = (boolean) shouldRecoverField.get(this);
			jobDataMap = (JobDataMap) jobDataMapField.get(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ServiceUnitJobDetail jobDetail = new ServiceUnitJobDetail();
		jobDetail.setJob(job);
		jobDetail.setJobClass(jobClass);
		jobDetail.setDescription(description);
        if(key == null){
            key = new JobKey(Key.createUniqueName(null), null);
        }
        jobDetail.setKey(key); 
        jobDetail.setDurability(durability);
        jobDetail.setRequestsRecovery(shouldRecover);
        
        if(!jobDataMap.isEmpty()){
        	jobDetail.setJobDataMap(jobDataMap);
        }
        return jobDetail;
    }
}
